package cn.wolfcode.service.impl;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.domain.AccountLog;
import cn.wolfcode.domain.AccountTransaction;
import cn.wolfcode.domain.OperateIntergralVo;
import cn.wolfcode.mapper.AccountLogMapper;
import cn.wolfcode.mapper.AccountTransactionMapper;
import cn.wolfcode.mapper.UsableIntegralMapper;
import cn.wolfcode.service.IUsableIntegralService;
import cn.wolfcode.web.msg.IntergralCodeMsg;
import com.alibaba.fastjson.JSON;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
@Slf4j
public class UsableIntegralServiceImpl implements IUsableIntegralService {
    @Autowired
    private UsableIntegralMapper usableIntegralMapper;
    @Autowired
    private AccountTransactionMapper accountTransactionMapper;
    @Autowired
    private AccountLogMapper accountLogMapper;

    @Override
    public void payIntergral(OperateIntergralVo operateIntergralVo) {
        //插入积分变更记录
        insertAccountLog(operateIntergralVo, AccountLog.TYPE_DECR);
        //减少积分
        int count = usableIntegralMapper.decrIntergral(operateIntergralVo.getUserId(), operateIntergralVo.getValue());
        if (count == 0) {
            throw new BusinessException(IntergralCodeMsg.OP_INTERGRAL_ERROR);
        }
    }

    @Override
    @Transactional
    public void refundIntergral(OperateIntergralVo vo) {
        //插入积分变更记录
        insertAccountLog(vo, AccountLog.TYPE_INCR);
        //增加积分
        usableIntegralMapper.addIntergral(vo.getUserId(), vo.getValue());
    }

    /**
     * 创建分布式事务记录
     *
     * @param vo      积分订单参数vo对象
     * @param context 上下文对象
     * @param state   事务状态
     * @param type    积分变更类型
     */
    private void insertAccountTransaction(OperateIntergralVo vo, BusinessActionContext context, int state, String type) {
        AccountTransaction at = new AccountTransaction();
        at.setTxId(context.getXid());
        at.setActionId(context.getBranchId() + "");
        at.setUserId(vo.getUserId());
        at.setGmtCreated(new Date());
        at.setGmtModified(new Date());
        at.setAmount(vo.getValue());
        at.setType(type);
        at.setState(state);
        accountTransactionMapper.insert(at);
    }

    /**
     * 积分操作日志
     *
     * @param vo   vo对象
     * @param type 积分变更类型
     */
    private void insertAccountLog(OperateIntergralVo vo, int type) {
        AccountLog log = new AccountLog();
        log.setPkValue(vo.getPk());
        log.setAmount(vo.getValue());
        log.setGmtTime(new Date());
        log.setType(type);
        log.setInfo(vo.getInfo());
        accountLogMapper.insert(log);
    }

    @Override
    public void decrIntergralTry(OperateIntergralVo vo, BusinessActionContext context) {
        log.info("进入减积分try业务方法中...");
        //先插入事务记录，如果成功继续执行，如果失败，说明出现的悬挂，抛出异常.
        insertAccountTransaction(vo, context, AccountTransaction.STATE_TRY, AccountTransaction.DECR_TYPE);
        //对用户账户进行积分冻结操作
        int count = usableIntegralMapper.freezeIntergral(vo.getUserId(), vo.getValue());
        if (count == 0) {
            throw new BusinessException(IntergralCodeMsg.INTERGRAL_NOT_ENOUGH);
        }
    }

    @Override
    public void decrIntergralCommit(BusinessActionContext context) {
        log.info("进入减积分commit业务方法中...");
        AccountTransaction accountTransaction = accountTransactionMapper.get(context.getXid(), String.valueOf(context.getBranchId()));
        //二阶段提交的时候没有这条记录，属于异常的情况
        if (accountTransaction == null) {
            //通知管理员，处理问题
            throw new BusinessException(IntergralCodeMsg.OP_INTERGRAL_ERROR);
        }
        if (AccountTransaction.STATE_TRY == accountTransaction.getState()) {
            //事务状态处于try,执行commit操作即可
            OperateIntergralVo vo = JSON.parseObject(context.getActionContext().get("vo").toString(), OperateIntergralVo.class);
            insertAccountLog(vo, AccountLog.TYPE_DECR);
            //减少积分
            usableIntegralMapper.decrIntergral(vo.getUserId(), vo.getValue());
            //修改状态
            int count = accountTransactionMapper.updateAccountTransactionState(accountTransaction.getTxId(), accountTransaction.getActionId(), AccountTransaction.STATE_COMMIT, AccountTransaction.STATE_TRY);
            if (count == 0) {
                //把事务状态从try变成commit阶段失败,通知管理员，处理问题
                throw new BusinessException(IntergralCodeMsg.OP_INTERGRAL_ERROR);
            }
            //解冻积分
            usableIntegralMapper.commitChange(vo.getUserId(), accountTransaction.getAmount());
        } else if (AccountTransaction.STATE_COMMIT == accountTransaction.getState()) {
            //事务状态属于commit,现在继续执行commit,保证幂等性即可不需要做其他逻辑
        }else {
            //事务状态属于cancel,这种属于异常情况,通知管理员，处理问题
            throw new BusinessException(IntergralCodeMsg.OP_INTERGRAL_ERROR);
        }
    }

    @Override
    public void decrIntergralRollback(BusinessActionContext context) {
        log.info("进入减积分rollBack业务方法中...");
        //获取事务记录
        AccountTransaction accountTransaction =accountTransactionMapper.get(context.getXid(),String.valueOf(context.getBranchId()));
        OperateIntergralVo vo = JSON.parseObject(context.getActionContext().get("vo").toString(),OperateIntergralVo.class);
        if(accountTransaction==null){
            //说明try方法还没有执行，空回滚，需要插入一条事务记录,避免try方法执行.
            insertAccountTransaction(vo, context, AccountTransaction.STATE_CANCEL, AccountTransaction.DECR_TYPE);
            return;
        }
        if(AccountTransaction.STATE_TRY == accountTransaction.getState()){
            //事务状态处于try,执行cancel操作即可
            //修改状态
            int count = accountTransactionMapper.updateAccountTransactionState(accountTransaction.getTxId(),accountTransaction.getActionId(),AccountTransaction.STATE_CANCEL,AccountTransaction.STATE_TRY);
            if(count==0){
                //把事务状态从try变成commit阶段失败,通知管理员，处理问题
                throw new BusinessException(IntergralCodeMsg.OP_INTERGRAL_ERROR);
            }
            //解冻积分
            usableIntegralMapper.unFreezeIntergral(vo.getUserId(), accountTransaction.getAmount());
        }else if(AccountTransaction.STATE_CANCEL == accountTransaction.getState()){
            //事务状态属于cancel,现在继续执行cancel,保证幂等性即可不需要做其他逻辑
        }else{
            //事务状态属于commit,这种属于异常情况,通知管理员，处理问题
            throw new BusinessException(IntergralCodeMsg.OP_INTERGRAL_ERROR);
        }
    }

    @Override
    public void incrIntergralTry(OperateIntergralVo vo, BusinessActionContext context) {
        log.info("进入加积分的try业务方法");
        //创建事务操作记录
        insertAccountTransaction(vo, context, AccountTransaction.STATE_TRY, AccountTransaction.INCR_TYPE);
    }

    @Override
    public void incrIntergralCommit(BusinessActionContext context) {
        log.info("进入加积分的commit业务方法");
        //获取事务记录
        AccountTransaction accountTransaction = accountTransactionMapper.get(context.getXid(), context.getBranchId() + "");
        //获取参数封装vo对象
        OperateIntergralVo vo = JSON.parseObject(context.getActionContext("vo").toString(), OperateIntergralVo.class);
        if (accountTransaction == null) {
            throw new BusinessException(IntergralCodeMsg.INTERGRAL_OPT_ERROR);
        }

        //判断事务状态
        if (AccountTransaction.STATE_TRY == accountTransaction.getState()) {
            //增加加分
            usableIntegralMapper.addIntergral(vo.getUserId(), vo.getValue());
            //修改状态
            accountTransactionMapper.updateAccountTransactionState(context.getXid(), context.getBranchId() + "", AccountTransaction.STATE_COMMIT, AccountTransaction.STATE_TRY);
        } else if (AccountTransaction.STATE_COMMIT == accountTransaction.getState()) {
            //幂等性操作
        } else {
            throw new BusinessException(IntergralCodeMsg.INTERGRAL_OPT_ERROR);
        }
    }

    @Override
    public void incrIntergralRollback(BusinessActionContext context) {
        log.info("进入加积分的rollback业务方法");
        //获取事务记录
        AccountTransaction accountTransaction = accountTransactionMapper.get(context.getXid(), context.getBranchId() + "");
        //获取参数封装vo对象
        OperateIntergralVo vo = JSON.parseObject(context.getActionContext("vo").toString(), OperateIntergralVo.class);
        //判断事务状态
        if (AccountTransaction.STATE_TRY == accountTransaction.getState()) {
            //创建事务记录
            insertAccountTransaction(vo, context, AccountTransaction.STATE_CANCEL, AccountTransaction.INCR_TYPE);
            accountTransactionMapper.updateAccountTransactionState(context.getXid(), context.getBranchId() + "", AccountTransaction.STATE_CANCEL, AccountTransaction.STATE_TRY);
        } else if (AccountTransaction.STATE_CANCEL == accountTransaction.getState()) {
            //幂等性操作
        } else {
            throw new BusinessException(IntergralCodeMsg.INTERGRAL_OPT_ERROR);
        }
    }
}
